package com.nbicc.obs.service;

import com.nbicc.module.config.autoconfig.IBucketAutoConfiguration;
import com.nbicc.module.config.autoconfig.PublicBucketAutoConfiguration;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lilingyan
 * @Date 2018/8/31 13:55
 */
@Slf4j
@Service
public class ObsService {

    @Autowired
    private PublicBucketAutoConfiguration publicBucketAutoConfiguration;

    private String getSign(IBucketAutoConfiguration bucketAutoConfiguration , String objectKey){
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(bucketAutoConfiguration.getAk(),
                bucketAutoConfiguration.getSk(),
                bucketAutoConfiguration.getEndPoint());
        // 创建桶
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.PUT, bucketAutoConfiguration.getExpireSeconds());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "text/plain");
        request.setHeaders(headers);
        request.setBucketName(bucketAutoConfiguration.getBucketName());
        request.setObjectKey(objectKey);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        String returnUrl = response.getSignedUrl();
        // 关闭obsClient
        try {
            obsClient.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        log.info("生成一个签名" + "objectKey" + objectKey + "url" + returnUrl);

        return returnUrl;
    }


    public Map<String,String> getPublicBucketSignList(List<String> objectKeyList) {
        Map<String,String> objectKeyMap = new ConcurrentHashMap<>();
        objectKeyList
                .parallelStream()
                .distinct()
                .forEach( objectKey ->
                            objectKeyMap.put(objectKey , getPublicBucketSign(objectKey))
                        );
        return objectKeyMap;
    }

    public String getPublicBucketSign(String objectKey){
        return getSign(publicBucketAutoConfiguration , objectKey);
    }

}
